package com.health.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

@Component//加入spring容器
public class TokenFilter extends ZuulFilter {
    /**
     * 过滤器类型
     * 返回pre表示前置过滤,表示在请求路由route之前执行
     * @return
     */
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    /**
     * 过滤器执行顺序
     * 数字越小,优先级越高,可为负数,小于1表示路由前执行
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 过滤器是否需要被执行
     * true执行
     * false不执行
     * @return
     */
    @Override
    public boolean shouldFilter() {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        StringBuffer requestURL = request.getRequestURL();
        //StringBuffer不含contains比较字符串,需转为String
        String url = requestURL.toString();
        //打印请求的url
        System.out.println(url);

        //判断路径中含有该字符串,则执行过滤
        return url.contains("/view/");
    }

    /**
     * 过滤器的具体处理
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        //获取token,检查是否存在,存在放行,不存在拒绝路由,返回响应
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        //在请求头中获取token
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)){
            //过滤该请求,不让响应
            requestContext.setSendZuulResponse(false);
            //响应状态码
            requestContext.setResponseStatusCode(401);
            //返回内容的响应编码-解决中文乱码
            requestContext.getResponse().setContentType("text/html;charset=utf-8");
            //返回数据
            requestContext.setResponseBody("401,!拒绝访问,请先登录");
        }

            //返回null,放行
        return null;
    }
}
